//
//  AttentionPersonViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/7/28.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "AttentionPersonViewController.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "JSONKit.h"
#import "AddTagViewController.h"
#import "attentionPersonTableviewCell.h"
@interface AttentionPersonViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) UITableView *personTableview;
@property (strong, nonatomic) NSMutableArray *personArray;
@property (strong, nonatomic) NSMutableArray *persons;
@end

@implementation AttentionPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.persons = [[NSMutableArray alloc] init];
//    self.title = @"推荐关注";
//    self.navigationController.navigationBar.translucent = NO;
//    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor =[UIColor whiteColor];
    
    // Do any additional setup after loading the view.    
    UIButton *done = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 15 - 25, 30, 25, 25)];
    [done setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    [done addTarget:self action:@selector(doneWithPerson:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:done];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 1)];
    view.backgroundColor = [UIColor colorWithRed:0.863 green:0.866 blue:0.875 alpha:1.000];
    [self.view addSubview:view];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    title.font = [UIFont boldSystemFontOfSize:17];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"推荐关注";
    title.center = CGPointMake(self.view.frame.size.width / 2, 44);
    [self.view addSubview:title];
    self.personTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.personTableview.dataSource = self;
    self.personTableview.delegate = self;
    //    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _personTableview.showsVerticalScrollIndicator = NO;
    [self.personTableview setSeparatorColor:[UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000]];
    [self.view addSubview:self.personTableview];
    
    if ([self.personTableview respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.personTableview setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.personTableview respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.personTableview setLayoutMargins:UIEdgeInsetsZero];
    }
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 1)];
    line.backgroundColor = [UIColor colorWithRed:0.894 green:0.898 blue:0.902 alpha:1.00];
    [self.view addSubview:line];
    [self requestPerson];
}
#pragma mark -
#pragma mark tabview
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark -- cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (self.view.frame.size.height - 64 - 45) / 8;
}

#pragma mark -- cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _personArray.count;
}

#pragma mark -- 重用池
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"person";
    attentionPersonTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[attentionPersonTableviewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_personArray.count > 0) {
        cell.rankModel = _personArray[indexPath.row];
    }
    if ([_persons containsObject:cell.rankModel.id]) {
        [cell.attention setImage:[UIImage imageNamed:@"didattention"] forState:UIControlStateNormal];
        cell.relation.text = @"已关注";
    } else {
        [cell.attention setImage:[UIImage imageNamed:@"attention"] forState:UIControlStateNormal];
        cell.relation.text = @"加关注";
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    attentionPersonTableviewCell *cell = (attentionPersonTableviewCell *)[tableView cellForRowAtIndexPath:indexPath];
    Rank *model = _personArray[indexPath.row];
    if ([_persons containsObject:model.id]) {
        [_persons removeObject:model.id];
        [cell.attention setImage:[UIImage imageNamed:@"attention"] forState:UIControlStateNormal];
        cell.relation.text = @"加关注";
    } else {
        [_persons addObject:model.id];
        [cell.attention setImage:[UIImage imageNamed:@"didattention"] forState:UIControlStateNormal];
        cell.relation.text = @"已关注";
    }
}
- (void)doneWithPerson:(UIButton *)seder
{
    /* 向服务器发送用户信息
     *
     *
     */
    NSDictionary *dic = [NSDictionary dictionaryWithObject:_persons forKey:@"persons"];
    NSString *url = @"http://123.57.1.143/api/user/persons";
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
       [self closeWithNoPerson:seder];
}
- (void)closeWithNoPerson:(UIButton *)sender
{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.8f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromTop;
    transition.delegate = self;
    [self.view.superview.layer addAnimation:transition forKey:nil];
    [self.view removeFromSuperview];
    [[AppDelegate shareDelegate] chooseTabBarController];
}

- (void)requestPerson
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/discover?p=1"];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.personArray = [[NSMutableArray alloc] init];
        [self reloadRankDataWithResponseObject:responseObject pag:1];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)reloadRankDataWithResponseObject:(id)responseObject pag:(int)pag
{
    NSDictionary *data = [responseObject objectForKey:@"data"];
    for (NSDictionary *dic in data) {
        Rank *model = [[Rank alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [_personArray addObject:model];
        [_persons addObject:model.id];
    }
//    NSLog(@"%@",_persons);
//    NSDictionary *meta = [responseObject valueForKey:@"meta"];
//    if (meta != nil) {
//        pages = [[meta valueForKey:@"pages"] intValue];
//        if (pages == 1 || pag == pages) {
//            fotter.hidden = YES;
//        }
//    }
    if (_personArray.count > 0) {
        [_personTableview reloadData];
    }
}
//- (void)createPersonButton:(NSArray *)persons
//{
//    for (int i = 0; i < persons.count; i++) {
//        PersonsBtn *personBtn = [[PersonsBtn alloc] initWithFrame:CGRectMake((0.3125 * self.view.frame.size.width+1) * (i % 3) + 10, (0.3125 * self.view.frame.size.width+21) * (i / 3) + 74, 0.3125 * self.view.frame.size.width, 0.3125 * self.view.frame.size.width + 30)];
//        personBtn.tag = [[persons[i] valueForKey:@"personID"] intValue];
//        personBtn.backgroundColor = [UIColor clearColor];
//        [personBtn addTarget:self action:@selector(personBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        personBtn.selected = YES;
//        [_persons addObject:[persons[i] valueForKey:@"personID"]];
//        [personBtn.avatar setImageWithURL:[NSURL URLWithString:[persons[i] valueForKey:@"personAvatar"]] placeholderImage:nil];
//        personBtn.name.text = [persons[i] valueForKey:@"personName"];
//        [self.view addSubview:personBtn];
//    }
//}
//- (void)personBtnClick:(PersonsBtn *)sender
//{
//    if (sender.selected == YES) {
//        sender.stateImage.hidden = YES;
//        sender.selected = NO;
//         NSString *str = [NSString stringWithFormat:@"%ld", (long)sender.tag];
//        [_persons removeObject:str];
//    } else {
//        sender.selected = YES;
//        sender.stateImage.hidden = NO;
//        NSString *str = [NSString stringWithFormat:@"%ld", (long)sender.tag];
//        [_persons addObject:str];
//    }
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
